package com.example.administrator.exkotlin.net

import android.text.TextUtils
import android.util.Log
import com.example.administrator.exkotlin.net.HttpTheradPool.HttpFixedThreadPool
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL

/**
 * Author by lp,on 2020/8/26/026,16:17.
 */
class HttpURLRequstIml : IHttpRqust {
    private val TAG = "HttpURLRequstIml"
    private lateinit var mHttpUrlRunnable: HttpUrlRunnable

    //开始执行
    override fun <T> excute(listener: IHttpRqust.URlListener?, request: T) {
        mHttpUrlRunnable = HttpUrlRunnable(listener = listener, urlPath = request.toString())
        HttpFixedThreadPool.execute(mHttpUrlRunnable)
    }

    inner class HttpUrlRunnable(val listener: IHttpRqust.URlListener? = null, private val urlPath: String? = null) : Runnable {
        override fun run() {
            Log.i(TAG, "开始网络请求线程")
            val result = StringBuilder()
            //发起请求
            if (TextUtils.isEmpty(urlPath)) {
                Log.i(TAG, "链接为空，请重新输入")
                result.append("链接为空，请重新输入")
                return
            }
            var urlConnection: HttpURLConnection? = null
            try {
                val url = URL(urlPath)
                val urlConnection = url.openConnection() as HttpURLConnection
                urlConnection.apply {
                    connectTimeout = 8000
                    readTimeout = 8000
                }
                val input = urlConnection.inputStream
                //从下面获取到的输入流进行读取
                val reader = BufferedReader(InputStreamReader(input))
                reader.use {
                    reader.forEachLine {
                        result.append(it)
                    }
                }
                Log.i(TAG, result.toString())
                listener?.response(result.toString())
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                urlConnection?.disconnect()
            }

        }

    }
}

